%% @author wenqi_zheng
%% @doc @todo Add description to websocket_handler.

-module(websocket_handler).
-behaviour(cowboy_websocket_handler).

%% ====================================================================
%% API functions
%% ====================================================================
-export([init/3]).
-export([websocket_init/3]).
-export([websocket_handle/3]).
-export([websocket_info/3]).
-export([websocket_terminate/3]).

%%websocket 握手
init(_, Req, Opts) ->
	%%插入数据
	websocket_store:dirty_insert(self(), web),	
	{upgrade, protocol, cowboy_websocket}.
%%连接初始
websocket_init(_Type, Req, _Opts) ->
	%%连接一秒后 发送消息	
	erlang:start_timer(1000, self(), <<"Hello!">>),
	{ok, Req, {}}.
%%处理客户端发送投递的消息
websocket_handle({text, Msg}, Req, State) ->
	%% 把消息投递到其余的进程 这里可以 投递到 tcp socket  也可以投递的 websocket 这样就可以实现 服务支持多协议处理
	lists:foreach(fun([Pid, SocketType]) -> 
						  case SocketType of
							  tcp -> ok;    
							  web ->
								  case Pid == self() of
									  true -> ok;
									  false -> Pid!{chat,Msg}
								  end                              
						  end
				  end, websocket_store:dirty_lookall()),	
	{reply, {text, <<"That's what she said! ", Msg/binary >>}, Req, State};
websocket_handle(_Data, Req, State) ->
	{ok, Req, State}.

%% 处理erlang 发送的消息 
websocket_info({chat, Msg}, _Req, State)->
	io:format("websocket_chat ~p~n", [Msg]),
	{reply, {text,<<"Other say!", Msg/binary >>},_Req, State};

%% 处理     erlang:start_timer(1000, self(), <<"Hello!">>) 发送的消息
websocket_info({timeout, _Ref, Msg}, Req, State) ->
	{reply, {text, Msg}, Req, State};

websocket_info(_Info, Req, State) ->
	{ok, Req, State}.

%%断开socket
websocket_terminate(_Reason, _Req, _State) ->
	io:format("websocket_terminate ~n"),
	websocket_store:dirty_delete(self()),
	ok.


%% ====================================================================
%% Internal functions
%% ====================================================================


